'use strict'

let { User } = require('../models');
let auth = require('../utils/auth');

let index_fn = async (ctx, next) => {
    let username=ctx.session.userName;
    ctx.render("index.html")
}


let login_fn = async (ctx, next) => {
    ctx.render("login.html")
}

let register_fn = async (ctx, next) => {
    ctx.render("register.html")
}

let loginDone_fn = async (ctx, next) => {
    let uid = ctx.request.body.username.trim() || '';
    let pwd = ctx.request.body.password.trim() || '';
    let res = '';

    console.log(uid);
    console.log(pwd);


    if (uid.length > 0 && pwd.length > 0) {
        let row = await User.findOne({
            where: {
                username: uid,
                password: pwd
            }
        }
        )
        let u2Json = JSON.stringify(row);
        if (u2Json !== "null") {

            ctx.session.userId = row.id,
            ctx.session.userName = row.username,
            res = { Code: 200, msg: "登陆成功" }
        } else {
            res = { Code: 1000, msg: "用户名或密码错误，请重试！！！" }
        }
    } else {
        res = { Code, msg: "用户名和密码不能为空 ！！！" }
    }
    ctx.body = JSON.stringify(res);
}

let registerDone_fn = async (ctx, next) => {
    let username = ctx.request.body.username.trim() || '';
    let password = ctx.request.body.password.trim() || '';
    let confirmpassword = ctx.request.body.confirmpassword.trim() || '';

    console.log(username);
    console.log(password);
    console.log(confirmpassword);

    if (username.length > 0 && password.length > 0 && confirmpassword.length > 0 && password === confirmpassword) {
        let userDemo = await User.findOne({ where: { username: username } });
        console.log(JSON.stringify(userDemo));
        let res = '';

        // 如果有找到同名的用户，则返回提示消息，并且不创建用户；否则创建用户，并返回提示消息
        if (userDemo) {
            // msg='当前用户名已经注册，请确认后重试';
            res = { code: 1000, msg: '当前用户名已经注册，请确认后重试' };
        } else {
            let u1 = User.create({
                username: username,
                password: password
            });
            res = { code: 200, msg: '注册成功' };
        }

        ctx.body = JSON.stringify(res);
        // ctx.render('login.html');
    } else {
        console.log('用户名或密码不能为空；并且两次密码应该相同');
    }
};

let cancel_fn=async(ctx,next)=>{
    ctx.session=null;
    ctx.body={code:200,msg:'注销成功'};
}
module.exports = {
    "/": ["get",auth, index_fn],
    "/login": ["get",auth,login_fn],
    "/cancel": ["post",auth, cancel_fn],
    "/register": ["get", register_fn],
    "/loginDone": ["post", loginDone_fn],
    "/registerDone": ["post", registerDone_fn]
}